var util = require('../../utils/util.js');
var app = getApp();
var md5 = require("../../utils/md5.js");
const Upyun = require('../../utils/upyun-wxapp-sdk');
var phone = '';
var wxAuthFail = true;
const upyun = new Upyun({
  bucket: util.upyun_bucket,
  operator: util.upyun_opterator,
  getSignatureUrl: util.upyun_getSignUrl
})
Page({
  data: {
      util: util,
      minHeight: 0,
      userInfo:{},
      sex:["请选择性别","男","女"],
      careerDirectionOne:[],
      careerDirectionTwo:[],
      careerDirectionThree: [],
      careerDirectionOneIndex:0,
      careerDirectionTwoIndex:0,
      careerDirectionThreeIndex: 0,
      careerDirectionOneId: [],
      careerDirectionTwoId: [],
      careerDirectionThreeId: [],
      provinceLocation: [],
      provinceLocationIndex: 0,
      provinceId: [],
      cityLocation: [],
      cityLocationIndex: 0,
      cityId: [],
      areaLocation: [],
      areaLocationIndex: 0,
      areaId: [],
      sexIndex: 0,
      uploadImg:[],
      citysValue: [0, 0, 0],
      province: [],
      city: [],
      area: [],
      provinceSel: 0,
      citySel: 0,
      areaSel: 0,
      citysV:"请选择城市",
      pickerViewDisplay:"none",
      tx:"",
      isnew:0,
      citys:{},
      csel:[],
      cselid:[],
      
      ownerUid: '',

      imgWH: 0,
  },
  loadMore:function(){
      if(!noMore){
        page ++;
        this.load();
      }
  },
  onLoad: function(data){

    var that = this;

    var tc = app.get_tc();//简体繁体转换
    that.setData({
      tc: tc
    })
    var uid = data.uid;
    var isnew = data.new;
    wx.showToast({
      title: tc == 1 ?"加載中":'加载中',
      icon: 'loading',
      duration: 3000
    })

    that.setData({
      sex: tc == 1 ? ["請選擇性別", "男", "女"] : ["请选择性别", "男", "女"],
      citysV: tc == 1 ? "請選擇城市":"请选择城市",
    })
    var titlename = tc == 1 ? '完善資料' : '完善资料';
    wx.setNavigationBarTitle({
      title: titlename,
    }); 


    this.setData({
      ownerUid: uid
    })

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          minHeight: res.windowHeight - 45,
          imgWH: (res.windowWidth - 18) / 4 - 12
        });
      }
    });
    this.getLoginInfo();
    // var citys = city.getCity();
    app.GetUserInfo(uid, function(res){
  
      // if(res.province > 0) {
      //   that.setCity(citys[res.province].areas);
      //   if (citys[res.province].areas && citys[res.province].areas[res.city]) {
      //     that.setArea(citys[res.province].areas[res.city].areas);
      //   }
      // }
      // phone = res.phone;
      // //更新数据
      // that.setData({
      //   userInfo:res,
      //   uploadImg:res.photo.split(','),
      //   sexIndex:res.sex,
      //   zhiyeIndex: res.zhiye,
      //   provinceSel:res.province,
      //   // citySel:res.city,
      //   areaSel:res.area,
      //   isnew: isnew,
      //   csel: res.usercata.split(','),
      //   cselid: res.usercataxcx.split(',')
      // }) 
      wx.hideToast();
      // if (res.province && citys[res.province]){
      //   that.setCity(citys[res.province].areas);
      // }
    });
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "usercata"
      },
      success: function(responseData){
        var resData = [];
        var resId = [];
        for(var i=0 ; i<responseData.data.length ; i++){
          resData = resData.concat([responseData.data[i].title]);
          resId = resId.concat([responseData.data[i].user_category_id]);
        }
        that.setData({
          careerDirectionOne:["第一身份"].concat(resData),
          careerDirectionTwo:["第二身份"].concat(resData),
          careerDirectionThree:["第三身份"].concat(resData),
          careerDirectionOneId: [0].concat(resId),
          careerDirectionTwoId: [0].concat(resId),
          careerDirectionThreeId: [0].concat(resId),
        });
      }
    });
    this.load();

    var province = [{ "title": "省","areas":{}}];
    var provinceLocation = ["省"];
    var provinceId = [];
    // for (var key in citys) {
    //   province = province.concat([citys[key]]);
    //   provinceLocation = provinceLocation.concat([citys[key].title]);
    //   provinceId = provinceId.concat([citys[key].area_id]);
    // }
    console.log(province);
    this.setData({
      // citys: citys,
      province: province,
      provinceLocation: provinceLocation,
      provinceId:provinceId
    });
    // if (this.data.provinceSel){
    //   this.setCity(citys[this.data.provinceSel].areas);
    // } else {
    //   this.setCity(province[0].areas);
    // }
  },
  // setCity: function (areas) {
  //   var city = [{ "title": "市", "areas": {} }];
  //   var cityLocation = ["市"];
  //   var cityId = [];
  //   for (var key in areas) {
  //     city = city.concat([areas[key]]);
  //     cityLocation = cityLocation.concat([areas[key].title]);
  //     cityId = cityId.concat([areas[key].area_id])
  //   }
  //   this.setData({
  //     city: city,
  //     area:[],
  //     cityLocation: cityLocation,
  //     areaLocationIndex: 0,
  //     cityId: cityId
  //   });
  //   if (this.data.citySel) {
  //     this.setArea(this.data.citys[this.data.provinceSel]['areas'][this.data.citySel].areas);
  //   } else {
  //     this.setArea(city[0].areas);
  //   }
  // },
  setArea: function (areas) {
    var area = [{ "title": "区" }];
    var areaLocation = ["区"];
    var areaId = [];
    for (var key in areas) {
      area = area.concat([areas[key]]);
      areaLocation = areaLocation.concat([areas[key].title]);
      areaId = areaId.concat([areas[key].area_id])
    }
    this.setData({
      area: area,
      areaLocation: areaLocation,
      areaId: areaId
    });
  },
  load:function(){
    var that = this;
  },
  bindPickerChange: function(e){
    var name = e.currentTarget.dataset.name;
    if(name == "cd"){
      this.setData({
        careerDirectionIndex: e.detail.value
      })
    } else if (name == "province") {
      this.setData({
        provinceLocationIndex: e.detail.value,
        // cityLocation: [],
        // cityLocationIndex: 0,
        // citySel: 0,
        areaSel: 0
      });
      this.setCity(this.data.province[e.detail.value].areas);
    } else if (name == "city") {
      this.setData({
        // cityLocationIndex: e.detail.value,
        areaLocation: [],
        areaLocationIndex: 0
      })
      this.setArea(this.data.city[e.detail.value].areas);
    } else if (name == "area") {
      this.setData({
        areaLocationIndex: e.detail.value
      })
    }else if(name == "sex"){
      this.data.userinfo.sex = e.detail.value;
      this.setData({
        // sexIndex: e.detail.value,  
        userinfo: this.data.userinfo      
      })
      console.log('this.data.userinfo.sex', this.data.userinfo.sex)
    }else if(name == "one"){
      this.setData({
        csel:[],
        careerDirectionOneIndex: e.detail.value
      })
    }else if(name == "two"){
      this.setData({
        careerDirectionTwoIndex: e.detail.value
      })
    }else if(name == "three"){
      this.setData({
        careerDirectionThreeIndex: e.detail.value
      })
    }
  },
  saveCard: function(e){
    app.saveFormId(e.detail.formId);
    var that = this;
    var tmpmd5 = md5.hexMD5(app.globalData.userInfo.uid + "usercominfo" + app.globalData.userInfo.token);
    var toastStr = '';
    if (!e.detail.value.name) { toastStr = '请输入姓名';}
    if (!e.detail.value.moble) { toastStr = '请输入手机号码'; }
    // if (!e.detail.value.one) { toastStr = '请选择职业'; }
    // // if (!e.detail.value.qm) { toastStr = '请输入签名'; }
    // if (!e.detail.value.wx) { toastStr = '请输入微信号'; }
    // if (!e.detail.value.email) { toastStr = '请输入邮箱地址'; }
    // if (!e.detail.value.province) { toastStr = '请选择省份'; }
    // if (!e.detail.value.city) { toastStr = '请选择城市'; }
    // if (!e.detail.value.address) { toastStr = '请输入地址'; }
    if (toastStr){
      wx.showToast({
        title: toastStr,
        icon: 'loading',
        duration: 1000
      })
    } else {

      var nowd = new Date();
      var nowm = nowd.getMonth() + 1;
      nowm = nowm.toString();
      if (parseInt(nowm) < 10) {
        nowm = '0' + nowm;
      }
      var nowda = nowd.getDate();
      nowda = nowda.toString();
      if (parseInt(nowda) < 10) {
        nowda = '0' + nowda;
      }
      var nowhour = nowd.getHours();
      nowhour = nowhour.toString();
      if (parseInt(nowhour) < 10) {
        nowhour = '0' + nowhour;
      }
      wx.showToast({
        title: '资料保存中',
        icon: 'loading',
        duration: 2000
      })
      
      var areaId = e.detail.value.area ? e.detail.value.area : '';
      var params = {
        "privatekey": tmpmd5, 
        "ac": "usercominfo",
        "uid": that.data.ownerUid,
        "edituid": app.globalData.userInfo.uid,
        "realname": e.detail.value.name,
        "phone": e.detail.value.moble,
        "companyName":e.detail.value.companyName,
        // "phone": phone,
        "avatar": e.detail.value.txval,
        // "usercata": e.detail.value.one + (e.detail.value.two ? ',' + e.detail.value.two : '') + (e.detail.value.three ? ',' + e.detail.value.three : ''),
        "usercata": '',
        // "myword": e.detail.value.qm,
        "myword": '',
        "weixin": e.detail.value.wx,
        // "weixin": wxname,
        "email": e.detail.value.email,
        "province": e.detail.value.province,
        "city": e.detail.value.city,
        "area": areaId, 
        "address": e.detail.value.address,

        "addresschoose": that.data.userinfo.addresschoose,
        "lon": that.data.userinfo.lon,
        "lat": that.data.userinfo.lat,
        "userjob": e.detail.value.userjob,
        "profession": e.detail.value.profession,
        "sex": that.data.userinfo.sex,
        "photos": that.data.uploadImg.map(function (item) { return item.replace('wxfile://tmp_', 'https://img.maxdoge.com/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/') }).join(','),
        "intro": e.detail.value.desc
      };
      console.log("编辑资料params：", params);
      util.api({
        data: params,
        method: "POST",
        success: function (responseData) {
          console.log(responseData);
          if(responseData.data.res){
            wx.removeStorageSync('userInfo');
            app.dialogToast("编辑成功", "success", function(){
              
              if(util.orgid == 17784){
                 wx.navigateBack({ url: '/pages/talent-mycard/talent-mycard' });
                  // wx.navigateBack({
                  //   delta: 1
                  // })
              }else{
                wx.reLaunch({ url: '/pages/mine/mine' });
              }
              
            });
          } else {
            wx.showToast({
              title: responseData.data.msg,
            })
          }
        }
      });
    }
    // var alertNam = {
    //   txval: "头像", name: "姓名", moble: "手机", yzm: "验证码", one: "的第一身份", address: "地址", city: "市", desc: "个人介绍", email: "邮箱", moble: "手机", name: "姓名", one: "第一身份", province: "省", qm: "签名", sex: "性别", txval: "头像", wx: "微信号", yzm: "验证码"};
    // for (var i in e.detail.value) {
    //     console.log(e.detail.value[i]);
    //     if(!e.detail.value[i]) {
    //       console.log(i);
    //     }
    // }

    // var data = this.data.careerDirectionData
    // var value = this.data.value;
    // console.log(data);
    // var careerDirection = [];
    // for(var i=0;i<value.length;i++){
    //   if(value[i] != 0)
    //     careerDirection = careerDirection.concat(data[value[i]].user_category_id);
    // }
    //careerDirection这个是职业方向的分类id
  },
  bindChange: function(e){
    var val = e.detail.value;
    // var citysValue = this.data.citysValue;
    var newVal = val;
    // console.log(val, citysValue);
    // if (val[0] != citysValue[0]){
    //   this.setCity(this.data.province[val[0]].areas);
    // }
    // else if (val[1] != citysValue[1]) {
    //   this.setArea(this.data.city[val[1]].areas);
    // }
    // this.setData({
    //   citysValue: newVal
    // });
    
  },
  showPickerView: function(){
    this.setData({
      pickerViewDisplay:"block"
    });
  },
  hidePickerView: function(){
    this.setData({
      pickerViewDisplay:"none"
    });
  },
  changePhone: function(event) {
    phone = event.detail.value;
  },
  sendCode: function() {
    util.api({
      data: {
        "publickey": util.publiccode,
        "phone": phone,
        "ac": "sendsmsmob"
      },
      success: function (responseData) {
        console.log(responseData);
        if (responseData.data.res == true) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success',
            duration: 1000
          })
        } else {
          wx.showToast({
            title: '手机号有误',
            icon: 'success',
            duration: 1000
          })
        }
      }
    });
  },
  pickerViewVal: function(){
    var province = this.data.province;
    // var city = this.data.city;
    var area = this.data.area;
    // var v = this.data.citysValue;
    // var citysV = province[v[0]].title + "," + city[v[1]].title;
    if(area.length != 0){
      // citysV += "," + area[v[2]].title;
    }
    this.setData({
      // citysV: citysV,
      pickerViewDisplay:"none"
    });
  },
  uploadImg: function(){
    var that = this;
    var photos = this.data.uploadImg;
    wx.chooseImage({
      count: 9, 
      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {
        const tempFilePaths = res.tempFilePaths;
        for (var photoi = 0; photoi < tempFilePaths.length; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda)+'/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {

              wx.showToast({
                title: '上传成功',
                icon: 'success',
                duration: 1000
              })

              that.setData({
                uploadImg: tempFilePaths.concat(photos)
              })
              for (var j = 0; j < that.data.uploadImg.length; j++) {
                console.log('img array = ', that.data.uploadImg[j]);
              }
            },
            fail: function ({errMsg}) {
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
      },
      fail: function ({errMsg}) {
        console.log('chooseImage fail, err is', errMsg)
      }
      // success: function (res) {
      //   var tempFilePaths = res.tempFilePaths;
      //   that.setData({
      //     uploadImg: tempFilePaths.concat(photos)
      //   });
      //   console.log(that.uploadImg);
      // }
    });
  },
  uploadTX: function () {
    var that = this;
    wx.chooseImage({
      count: 1,

      sizeType: ['compressed'],
      sourceType: ['album'],
      success: function (res) {

        const imageSrc = res.tempFilePaths[0]
        const avatarUrl = '/avatar/xcx/' + imageSrc.split('_')[1]
        upyun.upload({
          localPath: imageSrc,
          remotePath: avatarUrl,
          success: function (res) {

            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 1000
            })
          
            that.setData({
              tx: util.upyun_imgHost + avatarUrl
            })
          },
          fail: function ({errMsg}) {
            console.log('uploadImage fail, errMsg is', errMsg)
          }
        })
      },
      fail: function ({errMsg}) {
        console.log('chooseImage fail, err is', errMsg)
      }

      
    });
  },

  notEdit:function(){
    wx.showToast({
      title: '不能修改',
    })
  },

  uploadImgs: function () {
    var that = this;
    var photos = this.data.uploadImg;
    if (photos.length > 1) {
      app.dialog('只能传一张二维码', 'loading');
      return false;
    }

    wx.chooseImage({
      count: (9 - photos.length),
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        wx.showLoading({ title: '图片上传中..', mask: 'true' });
        const tempFilePaths = res.tempFilePaths;
        const tempFileCount = tempFilePaths.length;
        var uploadCount = 0;
        that.setData({
          uploadImg: tempFilePaths.concat(photos)
        })
        for (var photoi = 0; photoi < tempFileCount; photoi++) {
          var imageSrc = res.tempFilePaths[photoi]
          var nowd = new Date();
          var nowm = nowd.getMonth() + 1;
          nowm = nowm.toString();
          if (parseInt(nowm) < 10) {
            nowm = '0' + nowm;
          }
          var nowda = nowd.getDate();
          nowda = nowda.toString();
          if (parseInt(nowda) < 10) {
            nowda = '0' + nowda;
          }
          var nowhour = nowd.getHours();
          nowhour = nowhour.toString();
          if (parseInt(nowhour) < 10) {
            nowhour = '0' + nowhour;
          }
          var imgUrl = '/' + nowd.getFullYear().toString() + '/' + (nowm + nowda) + '/' + nowhour + '/' + imageSrc.split('_')[1]
          upyun.upload({
            localPath: imageSrc,
            remotePath: imgUrl,
            success: function (res) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              // jobj.put("url", recordUrl);
              // jobj.put("name", imgFileName);
              // jobj.put("type", resJob.optString("mimetype"));
              // jobj.put("size", resJob.optInt("file_size"));
              // jobj.put("hash", resJob.optString("sign"));
              // jobj.put("extension", resJob.optString("image-type"));
              // jobj.put("save_path", savePath);
              // jobj.put("save_name", savename);
              // jobj.put("width", resJob.optInt("image-width"));
              // jobj.put("height", resJob.optInt("image-height"));
            },
            fail: function ({ errMsg }) {
              uploadCount++;
              if (uploadCount == tempFileCount) {
                wx.showToast({
                  title: '上传成功',
                  icon: 'success',
                  duration: 1000
                })
              }
              console.log('uploadImage fail, errMsg is', errMsg)
            }
          })
        }
        //wx.hideLoading();
      },
      fail: function ({ errMsg }) {
        console.log('chooseImage fail, err is', errMsg)
      }
    });
  },
  //删除图片
  deleteImg: function (e) {
    var index = e.currentTarget.dataset.index;
    var photos = this.data.uploadImg;
    photos.splice(index, 1);
    this.setData({
      uploadImg: photos
    });
  },

  getLoginInfo: function(){
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        uid: res.uid,
        token: res.token
      });


      util.api({
        data: {
          "uid": res.uid,
          "publickey": util.publiccode,
          "ac": "userinfo"
        },
        success: function (responseData) {
 
          that.setData({
            userinfo: responseData.data,
            uploadImg:responseData.data.photo.split(','),
            // sexIndex:responseData.data.sex,
            zhiyeIndex: responseData.data.oldzhiye,
            // provinceSel:responseData.data.province,
            // // citySel:responseData.data.city,
            // areaSel:responseData.data.area,
            // isnew: isnew,
            // csel: responseData.data.usercata.split(','),
            // cselid: responseData.data.usercataxcx.split(',')
          });

          wx.hideToast();
        }
      });


    });
  },


  selectAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        console.log("选择地址：", res);
        var userinfo = that.data.userinfo;
        userinfo.addresschoose = res.address;
        userinfo.lon = res.longitude;
        userinfo.lat = res.latitude;
    
        that.setData({
          userinfo: userinfo
        })
      },
    })
  },

})